<template>
  <div class="dataContainer">
    <div class="main">
      <div class="drag-bar-header">
        <img
          src="@/assets/images/icon/标签页/关闭.png"
          @click="close"
          v-show="appendixDataShow"
        />
      </div>
      <el-tabs type="border-card" id="basicalData">
        <el-tab-pane label="基础信息" name="0">
          <!-- 基础信息表格 -->
          <el-table
            :data="basicalData"
            stripe
            :height="appendixDataShow ? 690 : ''"
          >
            <el-table-column prop="key" label="属性字段" width="150" />
            <el-table-column prop="value" label="项目数值" auto />
          </el-table>
          <!-- 附件列表 -->
          <el-tabs
            type="border-card"
            id="appendixData"
            v-show="appendixDataShow"
          >
            <el-tab-pane label="相关附件" name="0">
              <el-upload
                v-model:file-list="appendixData"
                class="upload-demo"
                multiple
                :on-preview="handleClick"
              >
                <template #tip>
                  <div class="el-upload__tip">点击下载附件</div>
                </template>
              </el-upload>
            </el-tab-pane>
          </el-tabs>
        </el-tab-pane>
        <el-tab-pane label="照片预览" name="1">
          <el-upload
            v-model:file-list="picList"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
          >
          </el-upload>
          <div class="emptyLegend" v-show="emptyShow">
            <img src="@/assets/images/icon/标签页/空盒子.png" />
            <p>暂无图层</p>
          </div>
        </el-tab-pane>
      </el-tabs>
      <!-- 底部按钮栏 -->
      <div class="controller">
        <!-- 用地查询 -->
        <div v-show="!appendixDataShow">
          <button @click="router.go(-1)" class="uploadButton">
            <img src="@/assets/images/icon/标签页/图层选择.png" />返回图层
          </button>
          <button @click="router.push('/mapLayout')" class="uploadButton">
            <img src="@/assets/images/icon/dataInput/去除.png" />关闭查询
          </button>
        </div>
        <!-- 标绘查询 -->
        <div v-show="appendixDataShow">
          <button id="cancel" @click="updateDrawing">
            <img src="@/assets/images/icon/dataInput/修改.png" />
            修改
          </button>
          <button id="submit" @click="confrimWindowShow = true">
            <img src="@/assets/images/icon/dataInput/去除.png" />
            删除
          </button>
        </div>
      </div>
    </div>
    <el-dialog
      v-model="confrimWindowShow"
      title="是否删除此标绘？"
      width="100%"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <template #footer>
        <span class="dialog-footer">
          <el-button type="danger" @click="confrimWindowShow = false">
            <img src="@/assets/images/icon/dataInput/取消.png" />
            <span> 取消</span>
          </el-button>
          <el-button type="success" @click="deleteDrawing">
            <img src="@/assets/images/icon/dataInput/确认.png" />
            <span> 确认</span>
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
/* eslint-disable */
import { getCurrentInstance, onMounted } from "vue";
import pubsub from "pubsub-js";
import { useRoute } from "vue-router";
import { useRouter } from "vue-router";
import axios from "axios";

import urlList from "@/store/urlList.json";
import message from "@/components/Message/showMessage";

export default {
  name: "dataContainer",
  data() {
    return {
      drawer: false,
      subList: [],
      basicalData: [],
      appendixData: [],
      appendixDataShow: true,
      fromPath: "",
      picList: [],
      confrimWindowShow: false,
      emptyShow: true,
    };
  },
  setup() {
    const { proxy } = getCurrentInstance();
    const route = useRoute();
    const router = useRouter();

    onMounted(() => {
      setTimeout(() => {
        pubsub.publish("toDetail");
      }, 500);
      subscribeList();
      // 入口分流
      switch (route.query.type) {
        case "mapDrawingSelect":
          getDetail();
          getAppendix();
          getPhoto();
          break;
        case "landuseSelect":
          proxy.basicalData = JSON.parse(route.query.dataList);
          proxy.appendixDataShow = false;
          break;
      }
    });

    // pubsub订阅列表
    function subscribeList() {
      proxy.subList.push(
        pubsub.subscribe("drawingDetailData", (n, data) => {
          proxy.basicalData = [];
          proxy.appendixData = [];
          getDetail(data.id);
          getAppendix(data.id);
          getPhoto(data.id);
        })
      );
    }

    // 读取数据库中标注的详细信息
    function getDetail(id = route.query.id) {
      // console.log(id);
      // 访问服务器
      axios({
        method: "get",
        url: urlList.serverURL + "getBasicalData",
        params: { id },
      }).then((res) => {
        console.log(res.data.code === 1 ? "读取成功" : "读取失败");
        message(res.data.msg, res.data.code === 1 ? "" : "error");
        console.log(res.data.result);
        // 分离键值对
        let dataList = JSON.parse(res.data.result[0].textDataList);
        // 标注基本信息填入表格
        proxy.basicalData = [];
        proxy.basicalData = dataList;
        // 时间戳
        let valueList = lengthCutting(res.data.result[0].id.split("_")[1], 2);
        let unitList = ["月", "日", "时", "分"];
        let time = "";
        for (let i = 0; i < unitList.length; i++) {
          time += valueList[i] + unitList[i];
        }
        proxy.basicalData.unshift({
          key: "创建时间",
          value: time,
        });
      });
    }

    // 字符串截取
    function lengthCutting(str, num) {
      if (str == null || str == undefined) return null;
      if (!/^[0-9]*[1-9][0-9]*$/.test(num)) return null;
      let array = new Array(),
        len = str.length;
      for (let i = 0; i < len / num; i++) {
        if ((i + 1) * num > len) {
          array.push(str.substring(i * num, len));
        } else {
          array.push(str.substring(i * num, (i + 1) * num));
        }
      }
      return array;
    }

    //  读取标注附件名称
    function getAppendix(id = route.query.id) {
      // 访问服务器
      axios({
        method: "get",
        url: urlList.serverURL + "getAppendixName",
        params: { id },
      }).then((res) => {
        console.log(res.data.code === 1 ? "读取成功" : "读取失败");
        message(res.data.msg, res.data.code === 1 ? "" : "error");
        proxy.appendixData = [];
        // 存入附件名数组
        res.data.result.forEach((element) => {
          proxy.appendixData.push({
            name: element.name + "." + element.type,
          });
        });
        // console.log(proxy.appendixData);
      });
    }

    // 附件点击下载
    function handleClick() {
      let fileName = event.target.innerHTML.split(".")[0];
      let fileType = event.target.innerHTML.split(".")[1];
      let id = route.query.id;
      // 读取附件文件
      axios({
        method: "get",
        url: urlList.serverURL + "getAppendixData",
        params: { id, fileName },
      }).then((res) => {
        console.log(res.data.code === 1 ? "读取成功" : "读取失败");
        let file = res.data.result[0].data;
        downloadFile(dataURLtoBlob(file), fileName, fileType);
      });
    }

    function dataURLtoBlob(dataurl) {
      var arr = dataurl.split(",");
      //注意base64的最后面中括号和引号是不转译的
      var _arr = arr[1].substring(0, arr[1].length - 2);
      var mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(_arr),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], {
        type: mime,
      });
    }

    // 下载附件文件
    function downloadFile(blob, fileName, fileType) {
      // var blob = new Blob([res]);
      const reader = new FileReader();
      reader.readAsDataURL(blob);
      reader.onload = (e) => {
        const a = document.createElement("a");
        a.download = `${fileName}.${fileType}`;
        a.href = e.target.result;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        message("附件正在导出");
      };
    }

    // 退出详细数据页面
    function close() {
      switch (proxy.fromPath) {
        case "/mapLayout":
          router.push({
            path: "/mapLayout",
          });
          break;
        case "/mapLayout/update":
          router.push({
            path: "/mapLayout",
          });
          break;
        case "/mapLayout/selectResult":
          router.go(-1);
          break;
      }
    }

    // 照片大图预览
    function handlePictureCardPreview(data) {
      pubsub.publish("bigPic", { picSrc: data.url, name: data.name });
    }

    // 读取标绘相关的照片
    function getPhoto(id = route.query.id) {
      proxy.picList = [];
      axios({
        method: "get",
        url: urlList.serverURL + "getPhoto",
        params: { id },
      }).then((res) => {
        res.data.result.forEach((element) => {
          proxy.picList.push({
            url: element.data,
            name: element.name + "." + element.type,
          });
        });
      });
    }

    // 删除标绘
    function deleteDrawing() {
      let id = route.query.id;
      // console.log(id);
      // 删除基础信息
      axios({
        method: "get",
        url: urlList.serverURL + "deleteBasicalData",
        params: { id },
      }).then((res) => {
        console.log(res.data.code === 1 ? "操作成功" : "操作失败");
        message(res.data.msg, res.data.code === 1 ? "" : "error");
      });
      // 删除附件信息
      axios({
        method: "get",
        url: urlList.serverURL + "deleteAppendixData",
        params: { id },
      }).then((res) => {
        console.log(res.data.code === 1 ? "操作成功" : "操作失败");
        message(res.data.msg, res.data.code === 1 ? "" : "error");
      });
      // 返回主页
      setTimeout(() => {
        close();
      }, 2000);
    }

    // 更新修改标绘
    function updateDrawing() {
      router.push({
        path: "/mapLayout/update",
        query: { id: route.query.id },
      });
    }

    return {
      handleClick,
      close,
      handlePictureCardPreview,
      deleteDrawing,
      updateDrawing,
      router,
    };
  },
  watch: {
    appendixData: {
      handler(newValue) {
        this.emptyShow = !newValue.length > 0;
      },
      deep: true,
    },
  },
  beforeDestroy() {
    this.subList.forEach((element) => {
      pubsub.unsubscribe(element);
    });
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.fromPath = from.path;
    });
  },
  beforeRouteLeave() {
    this.subList.forEach((element) => {
      pubsub.unsubscribe(element);
    });
  },
};
</script>

<style lang="less" scoped>
@import "../../assets/styles/variables.less";
.uploadButton {
  width: 30%;
  font-weight: normal;
  border: 1px solid @mainColor;
  padding-top: 1%;
  > img {
    margin-top: 2%;
    margin-right: 2%;
  }
}

.emptyLegend {
  text-align: center;
  > img {
    margin-top: 10%;
    width: 20%;
  }
}

.drag-bar-header {
  background-color: transparent;
  width: 50%;
  height: 50px;
  position: absolute;
  left: 50%;
  z-index: 9999;
  > img {
    width: 20px;
    float: right;
    position: relative;
    right: 2.5%;
    top: 7%;
  }
}
.main {
  background-color: white;
  height: 100%;
  > .el-tabs {
    border-radius: 5px !important;
  }
  > #basicalData {
    height: 95%;
  }
  > .controller {
    width: 100%;
    border-top: 2px solid @mainColor;
    background-color: white;
    box-shadow: -1px 0 3px 0.5px @mainColor;
    position: absolute;
    z-index: 99999;
    bottom: 0%;
    text-align: right;
    overflow: auto;
    padding: 2% 0%;
  }
}
button {
  border: 2px solid @mainColor;
  background-color: white;
  outline: none;
  padding: 0.1%;
  padding-bottom: 0%;
  border-radius: 5px;
  color: @mainColor;
  font-weight: bold;
  font-size: 130%;
  margin: 0.5%;
  > img {
    width: 25px;
    margin-right: -6%;
    display: inline-block;
    margin-bottom: 5%;
  }
  > span {
    > img {
      width: 25px;
      display: inline-block;
    }
  }
}
.dataContainer {
  position: absolute;
  top: 5.5%;
  right: 0.25%;
  height: 94%;
  width: 15%;
  background-color: white;
  z-index: 99999;
  border-radius: 5px;
  overflow: auto !important;
}
</style>